﻿@COFE ?= {}

$ = jQuery
utils = COFE.utils
Link = COFE.Link


class Search extends Spine.Controller
  constructor : ->
    super      
    @el.live("pageshow", (event, data) => 
      @onPageLoaded())

  elements : 
    ".startSearch" : "btnSearch"    
    "#root" : "txtRoot"
    "#subdir" : "cbSubdir"
    "#filename" : "txtFilename"
    "#filetype" : "txtFiletype"
    "#searchParam" : "txtSearchParam"

  events : 
    "keypress" : "OnKeyPressed"
    "click .startSearch" : "OnSearch"    
    "change #root" : "OnTextChanged"
    "change #subdir" : "OnTextChanged"    
    "change #filename" : "OnTextChanged"
    "change #filetype" : "OnTextChanged"

  OnKeyPressed : (e) =>
    if e.charCode is 13 #enter key
      @btnSearch.focus()
      @btnSearch.click()

  OnTextChanged : =>
    @updateSearchParam()

  OnSearch : =>
    searchFilter = @txtSearchParam.val()
    #console.log "search"  + searchFilter
    if searchFilter isnt ""
      @el.dialog('close')  
      @App.changePath(Link.fromSearch(searchFilter), "Search")              

  onPageLoaded : =>
    if @App.path.rel is "folder"
      @txtRoot.val(@App.path.param)
      @updateSearchParam()

  updateSearchParam : =>
    param = ""
    if (@txtRoot.val() isnt "")
      param += "root:" + @txtRoot.val()    
    if (@cbSubdir.attr("checked"))
      param += " subdir:true"
    if (@txtFilename.val() isnt "")
      param += " filename:" + @txtFilename.val()
    if (@txtFiletype.val() isnt "")
      for ftype, i in @txtFiletype.val().split(",")
        if i is 0 
        then param += " filetype:" + ftype.trim()
        else param += " OR filetype:" + ftype.trim()
    @txtSearchParam.val(param.trim())
        
COFE.Search = Search

